#define _CRT_SECURE_NO_WARNINGS 1
#include "SeqList.h"

void SLinit(SL* ps)
{
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}

void SLdelete(SL* ps)
{
	free(ps->arr);
	ps->arr = NULL;
	ps->size = 0;
	ps->capacity = 0;
}



static void SLCheck(SL* ps)
{
	if (ps->size == ps->capacity)
	{
		int newcapacity = ((ps->size == 0) ? 4 : (ps->capacity * 2));
		SLDatatype* tmp = (SLDatatype*)realloc(ps->arr, (size_t)newcapacity * sizeof(SLDatatype));
		if (tmp == NULL)
		{
			perror("realloc");
			exit(1);
		}
		ps->arr = tmp;
		ps->capacity = newcapacity;
	}
}

void SLPushBack(SL* ps, SLDatatype x)
{
	assert(ps);
	SLCheck(ps);
	ps->arr[ps->size++] = x;
}

void SLPushFront(SL* ps, SLDatatype x)
{
	assert(ps);
	SLCheck(ps);
	for (int i = ps->size - 1;i >= 0 ;i--)
	{
		ps->arr[i + 1] = ps->arr[i];
	}
	ps->arr[0] = x;
	++ps->size;
}

void SLPopBack(SL* ps)
{
	assert(ps);
	assert(ps->size);
	--ps->size;
}

void SLPopFront(SL* ps)
{
	assert(ps);
	assert(ps->size);
	for (int i = 0;i < ps->size - 1;i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	--ps->size;
}

void SLInsert(SL* ps, int pos, SLDatatype x)
{
	assert(ps);
	assert((0 <= pos) && (pos <= ps->size));
	SLCheck(ps);
	for (int i = ps->size;i > pos;i--)
	{
		ps->arr[i] = ps->arr[i - 1];
	}
	ps->arr[pos] = x;
	++ps->size;
}

void SLPop(SL* ps, int pos)
{
	assert(ps);
	assert((0 <= pos) && (pos < ps->size));
	//删除操作
	for (int i = pos;i < ps->size - 1;i++)
	{
		ps->arr[i] = ps->arr[i + 1];
	}
	--ps->size;
}
